﻿using DGZImp.MdsProject.Base;
using DGZImp.MdsProject.Devices.Base;
using DGZImp.MdsProject.Devices.Helper;
using DGZImp.MdsProject.Devices.Models;
using Microsoft.AspNetCore.Hosting.Server;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DGZImp.MdsProject.Devices
{
    /// <summary>
    /// 固定扫码器
    /// </summary>
    public class Scanner : BaseDevice
    {
        public ScannerData Data { get; set; }

        public Scanner(string id, string name, IIotServe serve) :
            base(id, name, serve)
        {
            serve.OnTcpDataReceive += DataReceiveHandler;
            Data = new ScannerData();
        }

        public void DataReceiveHandler(object sender, byte[] datas)
        {
            var data = Encoding.ASCII.GetString(datas);
            SetBarcode(data);
        }

        [MdsAction("启动扫码", "发送一个扫码指令")]

        public async Task SendOpenAsync()
        {
            var result = await ((TcpServe)Serve).WriteAsync(new byte[] { 0x16, 0x54, 0x0D });
            if (!result.IsSuccess)
            {
                throw new Exception(result.Message);
            }
        }

        [MdsAction("停止扫码", "发送一个停止扫码指令")]

        public async Task SendCloseAsync()
        {
            await ((TcpServe)Serve).WriteAsync(new byte[] { 0x16, 0x54, 0x0D });
        }

        public void SetBarcode(string barcode)
        {
            Data.PreBarcode = Data.Barcode;
            Data.PreScanTime = Data.ScanTime;
            Data.Barcode = barcode;
            Data.ScanTime = DateTime.Now;
        }

    }

    public class ScannerData
    {
        [Description("01.条码")]
        public string Barcode { get; set; }
        [Description("02.扫描时间")]
        public DateTime? ScanTime { get; set; }
        [Description("03.上一条码")]
        public string PreBarcode { get; set; }
        [Description("04.上一条码扫描时间")]
        public DateTime? PreScanTime { get; set; }
    }
}
